﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Networking;

namespace CJ.XNFZ.ILABX {
    public class ILABXHelper : Singleton<ILABXHelper> {

        public ILABXConfig config;

        public string file = "ilabx.json";

        public string username;
        public string nickname;

        public void GetConfig (Action ok = null, Action<string> error = null) {
            XNFZTemplateHelper.Instance.GetConfig (
                file,
                (string json) => {
                    config = JsonUtility.FromJson<ILABXConfig> (json);
                    if (ok != null) ok ();
                },
                (string e) => {
                    if (error != null) error ("获取配置文件错误");
                }
            );
        }

        public void Login (string username, string password, Action ok = null, Action<string> error = null) {
            StartCoroutine (_Login (username, password, ok, error));
        }

        public void Token (Action ok = null, Action<string> error = null) {
            StartCoroutine (_Token (ok, error));
        }

        public void Status (Action ok = null, Action<string> error = null) {
            StartCoroutine (_Status (ok, error));
        }

        /// <summary>
        /// 学生上传成绩到ilab平台
        /// </summary>
        /// <param name="ID">学生id</param>
        /// <param name="className">课程名字</param>
        /// <param name="status">是否完成； 1：完成  0：未完成</param>
        /// <param name="score">成绩</param>
        /// <param name="startTime">开始时间</param>
        /// <param name="endTime">结束时间</param>
        /// <param name="timeUsed">课程用时</param>
        /// <param name="issuerId">ilab平台特殊id标识</param>
        public void Log (string projectTitle, string childProjectTitle, int status, int score, long startDate, long endDate, int timeUsed, Action ok = null, Action<string> error = null) {
            StartCoroutine (_Log (projectTitle, childProjectTitle, status, score, startDate, endDate, timeUsed, ok, error));
        }

        // 传入：
        // {
        // "username":"balbalbalbala",
        // "password":"balbalbalbala"
        // }
        // 返回：
        // {
        // "code": 0,
        // "username": "mj_424948",
        // "name": "rengaru"
        // }
        IEnumerator _Login (string username, string password, Action ok = null, Action<string> error = null) {
            LoginReq body = new LoginReq ();
            body.username = username;
            body.password = password;
            byte[] postData = System.Text.Encoding.UTF8.GetBytes (JsonUtility.ToJson (body));
            var req = new UnityWebRequest (config.loginURL, "POST");
            req.uploadHandler = (UploadHandler) new UploadHandlerRaw (postData);
            req.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer ();
            req.SetRequestHeader ("Content-Type", "application/json");
            yield return req.SendWebRequest ();

            if (req.isNetworkError || req.isHttpError) {
                Debug.LogError ("login error：" + req.responseCode + " " + req.downloadHandler.text);
                if (error != null) error (req.error);
            } else {
                //由于ilab平台所有返回值都是200，正确错误的消息放在了返回消息的code当中，所以需要打印response.DataAsText查看结果
                var res = JsonUtility.FromJson<LoginRes> (req.downloadHandler.text);
                if (res.code == 0) {
                    this.username = res.username;
                    this.nickname = res.name;
                    XNFZTemplateHelper.Instance.ShowName ("用户名（ilab-x.com）：" + this.nickname);
                    if (ok != null) ok ();
                } else {
                    Debug.LogError ("login error：" + req.responseCode + " " + req.downloadHandler.text);
                    if (error != null) error (req.error);
                }
            }
        }

        IEnumerator _Token (Action ok = null, Action<string> error = null) {
            TokenReq body = new TokenReq ();
            body.token = XNFZTemplateHelper.Instance.GetSearchString ("token");
            body.issuerId = config.issuerID;
            byte[] postData = System.Text.Encoding.UTF8.GetBytes (JsonUtility.ToJson (body));
            var req = new UnityWebRequest (config.tokenURL, "POST");
            req.uploadHandler = (UploadHandler) new UploadHandlerRaw (postData);
            req.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer ();
            req.SetRequestHeader ("Content-Type", "application/json");
            yield return req.SendWebRequest ();

            if (req.isNetworkError || req.isHttpError) {
                Debug.LogError ("login error：" + req.responseCode + " " + req.downloadHandler.text);
                if (error != null) error (req.error);
            } else {
                var res = JsonUtility.FromJson<TokenRes> (req.downloadHandler.text);
                this.username = res.un;
                this.nickname = res.dis;
                XNFZTemplateHelper.Instance.ShowName ("用户名（ilab-x.com）：" + this.nickname);
                if (ok != null) ok ();
            }
        }

        IEnumerator _Status (Action ok = null, Action<string> error = null) {
            StatusReq body = new StatusReq ();
            body.username = username;
            body.issuerId = config.issuerID;
            byte[] postData = System.Text.Encoding.UTF8.GetBytes (JsonUtility.ToJson (body));
            var req = new UnityWebRequest (config.statusURL, "POST");
            req.uploadHandler = (UploadHandler) new UploadHandlerRaw (postData);
            req.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer ();
            req.SetRequestHeader ("Content-Type", "application/json");
            yield return req.SendWebRequest ();

            if (req.isNetworkError || req.isHttpError) {
                Debug.LogError ("login error：" + req.responseCode + " " + req.downloadHandler.text);
                if (error != null) error (req.error);
            } else {
                //由于ilab平台所有返回值都是200，正确错误的消息放在了返回消息的code当中，所以需要打印response.DataAsText查看结果
                var res = JsonUtility.FromJson<StatusRes> (req.downloadHandler.text);
                if (res.code == 0) {
                    if (ok != null) ok ();
                } else {
                    Debug.LogError ("login error：" + req.responseCode + " " + req.downloadHandler.text);
                    if (error != null) error (req.error);
                }
            }
        }

        // 传入：
        // {
        // "username":"test",
        // "projectTitle":"在园幼儿气道异物阻塞急救处理虚拟仿真实验教学项目",
        // "childProjectTitle":"安全",
        // "status":1,
        // "score": 80,
        // "startDate":1562121035382,
        // "endDate":1562122135382,
        // "timeUsed":10,
        // "issuerId":"100226"
        // }
        // 返回：
        // {
        // "code": 0,
        // "id": "5164"
        // }

        IEnumerator _Log (string projectTitle, string childProjectTitle, int status, int score, long startDate, long endDate, int timeUsed, Action ok = null, Action<string> error = null) {
            LogReq body = new LogReq ();
            body.username = username;
            body.projectTitle = projectTitle;
            body.childProjectTitle = childProjectTitle;
            body.status = status;
            body.score = score;
            body.startDate = startDate;
            body.endDate = endDate;
            body.timeUsed = timeUsed;
            body.issuerId = config.issuerID;
            byte[] postData = System.Text.Encoding.UTF8.GetBytes (JsonUtility.ToJson (body));
            var req = new UnityWebRequest (config.logURL, "POST");
            req.uploadHandler = (UploadHandler) new UploadHandlerRaw (postData);
            req.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer ();
            req.SetRequestHeader ("Content-Type", "application/json");
            yield return req.SendWebRequest ();

            if (req.isNetworkError || req.isHttpError) {
                Debug.LogError ("login error：" + req.responseCode + " " + req.downloadHandler.text);
                if (error != null) error (req.error);
            } else {
                //由于ilab平台所有返回值都是200，正确错误的消息放在了返回消息的code当中，所以需要打印response.DataAsText查看结果
                var res = JsonUtility.FromJson<LogRes> (req.downloadHandler.text);
                if (res.code == 0) {
                    if (ok != null) ok ();
                } else {
                    Debug.LogError ("login error：" + req.responseCode + " " + req.downloadHandler.text);
                    if (error != null) error (req.error);
                }
            }
        }
    }
}